#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/3 15:10
# @Author : 吴敬超
# explain:
import pandas as pd
import numpy as np
import netCDF4 as nc
import logging
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

log_file = "./nc2csv.log"

logging.basicConfig(filename=log_file, level=logging.DEBUG)

infile = sys.argv[1]
variablename = sys.argv[2]
outcsvfile = sys.argv[3]

logging.info("infile is " + infile)
logging.info("variablename is " + variablename)
logging.info("outcsvfile is " + outcsvfile)

ncdt = nc.Dataset(infile)
res = []

listvarcsnames = []
csvheads = []
# csv 头文件字段

for dim in ncdt.variables[variablename].get_dims():
    logging.info("variable  every dimensions is " + dim.name)
    csvheads.append(dim.name)

    listvarcsnames.append(ncdt.variables[dim.name][:])
# csvheads = listvarcsnames
csvheads.append(variablename)
# print "csvheads is "
#
# print csvheads

tocsvvar = ncdt.variables[variablename][:]


def change(changlist):
    """
    检查list元素是否全部为0
    :param changlist:
    :return:
    """
    for changei in changlist:

        if changei != 0:
            return False
    return True


def tocsv(rlist, dtlist, outpath=outcsvfile, vlsit=listvarcsnames, csvheadlist=csvheads):
    """
    生成csv文件，生成的文件没有头文件
    :param rlist:生成csv 前n列对应
    :param dtlist: csv文件最后一个字段对应的list
    :param outpath: 生成的csv 文件
    :param vlsit: 变量参数集合的list
    :param csvheadlist: csv文件的表头

    :return:
    """

    # logging.info("run tocsv")
    dict = {}
    headerflag = change(rlist)

    for i in range(len(csvheadlist) - 2):
        dict[csvheadlist[i]] = vlsit[i][rlist[i]]

    # print dict
    dict[csvheadlist[-2]] = listvarcsnames[-1]
    dict[csvheadlist[-1]] = dtlist

    dataframe = pd.DataFrame(dict)

    # 生成的csv字段会根据字典排序，通过指定columns确定顺序 ,mode="a" 追加，line_terminator = '\n' 换行,header=False没有csv表头
    dataframe.to_csv(outpath, columns=csvheadlist, header=headerflag, index=False, sep=',', mode="a",
                     line_terminator='\n')


def bianli(lists, result):
    """
    递归遍历变量
    :param lists: 需要转成csv的变量
    :param result: 记录下标的list
    :return:
    """
    for i, val in enumerate(lists):

        # print ("val ndim is ", val.ndim)
        r = []
        r.extend(result)
        r.append(i)
        # print (r)

        if val.ndim == 1:
            # print ("******rrrrrrr*******", r)

            tocsv(r, val)
            continue
        if type(val) != np.ma.core.MaskedArray:
            logging.info("递归到底")
            # print ("递归到底")

        else:

            logging.info("递归没有到底")
            # print ("递归没有到底")
            bianli(val, r)


if __name__ == "__main__":

    try:
        bianli(tocsvvar, res)
        ncdt.close()
    except BaseException:
        # 0表示转文件失败
        print 0
    else:
        # 1表示转文件成功
        print 1
